package com.wuxianedu.loadimage;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by TED on 2016/9/30.
 */
public class GridAdapter extends BaseAdapter {
    Context mContext;
    String[] urls;

    public GridAdapter(Context mContext, String[] urls) {
        this.mContext = mContext;
        this.urls = urls;
    }

    @Override
    public int getCount() {
        return urls.length;
    }

    @Override
    public Object getItem(int position) {
        return urls[position];
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = View.inflate(mContext, R.layout.item_grid, null);
        }

        final ImageView image = (ImageView) convertView.findViewById(R.id.image_view);


//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                try {
//                    URL url = new URL(urls[position]);
//                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//                    if (conn.getResponseCode() == 200) {
//                        final Bitmap bitmap = BitmapFactory.decodeStream(conn.getInputStream());
//
//                        ((AppCompatActivity) mContext).runOnUiThread(new Runnable() {
//                            @Override
//                            public void run() {
//                                image.setImageBitmap(bitmap);
//                            }
//                        });
//
//                    }
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//
//            }
//        }).start();


        loadImageUtil.loadImage(urls[position],image, new loadImageUtil.LoadImageListener() {

            @Override
            public void loadImageSuccess(final Bitmap bitmap,final String url,final ImageView imageView) {
                ((AppCompatActivity)mContext).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        imageView.setImageBitmap(bitmap);
                        imageView.setTag(url);
                    }
                });
            }

            @Override
            public void loadImageFailed() {

            }
        });

        return convertView;
    }
}
